package com.strong.config.security.handler;

import com.strong.utils.mvc.pojo.view.ReplyEnum;
import com.strong.utils.mvc.pojo.view.ReplyVO;
import com.strong.utils.security.SecurityUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * jwt验证故障处理程序
 *
 * @author Simen
 * @date 2022/02/15
 */
@Slf4j
@Component("JwtAuthenticationFailureHandler")
public class JwtAuthenticationFailureHandler implements AuthenticationFailureHandler {

    public static final String LOGIN_ERROR_ACCOUNT_LOCKING = "账户锁定";
    public static final String LOGIN_ERROR_PASSWORD_EXPIRED = "密码过期";
    public static final String LOGIN_ERROR_OVERDUE_ACCOUNT = "账户过期";
    public static final String LOGIN_ERROR_ACCOUNT_BANNED = "账户被禁止";
    public static final String LOGIN_ERROR_USER_CREDENTIAL_EXCEPTION = "登录密码错误";
    public static final String LOGIN_ERROR_USER_NAME_NOT_FOUND = "用户名未找到异常";
    public static final String LOGIN_ERROR_UNKNOWN = "用户权限未知异常";
    public static final String LOGIN_ERROR = "用户权限异常";

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException {
        String strData = LOGIN_ERROR_UNKNOWN;
        String strMessage = "LOGIN_ERROR_UNKNOWN";

        if (exception instanceof LockedException) {
            strData = LOGIN_ERROR_ACCOUNT_LOCKING;
            strMessage = exception.getMessage();
        } else if (exception instanceof CredentialsExpiredException) {
            strData = LOGIN_ERROR_PASSWORD_EXPIRED;
            strMessage = exception.getMessage();
        } else if (exception instanceof AccountExpiredException) {
            strData = LOGIN_ERROR_OVERDUE_ACCOUNT;
            strMessage = exception.getMessage();
        } else if (exception instanceof DisabledException) {
            strData = LOGIN_ERROR_ACCOUNT_BANNED;
            strMessage = exception.getMessage();
        } else if (exception instanceof BadCredentialsException) {
            strData = LOGIN_ERROR_USER_CREDENTIAL_EXCEPTION;
            strMessage = exception.getMessage();
        } else if (exception instanceof UsernameNotFoundException) {
            strData = LOGIN_ERROR_USER_NAME_NOT_FOUND;
            strMessage = exception.getMessage();
        }

        // exception.printStackTrace();
        SecurityUtils.returnReplyJsonResponse(response, HttpServletResponse.SC_OK,
                new ReplyVO<>(strData, strMessage, ReplyEnum.ERROR_USER_HAS_NO_PERMISSIONS.getCode()));
    }

}
